package com.xpgk.mvc.buyProduct;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantRender;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.bentryRegister.BentryRegisterService;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.bentryRegister.CustomerAgreement;
import com.xpgk.mvc.bentryRegister.CustomerDetail;
import com.xpgk.mvc.bentryRegister.CustomerProduct;
import com.xpgk.mvc.bentryRegister.CustomerProductSurplus;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.productOrgExperience.ProductOrgExperience;
import com.xpgk.mvc.productPrice.ProductPrice;
//import com.xpgk.mvc.product.Product;
import com.xpgk.mvc.productSales.ProductSales;
import com.xpgk.mvc.productSales.ProductSalesOrder;
import com.xpgk.mvc.productStock.ProductStock;
import com.xpgk.mvc.productStock.ProductStockInfo;
import com.xpgk.mvc.statistic.dailyTotalStatistic.DailyNursingTotal;
import com.xpgk.mvc.statistic.monthTotalStatistic.MonthTotal;
import com.xpgk.mvc.statistic.yearTotalStatistic.YearTotal;
//import com.xpgk.mvc.product.ProductSales;
//import com.xpgk.mvc.product.ProductStock;
//import com.xpgk.mvc.product.ProductStockInfo;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.tools.ToolDateTime;
import com.xpgk.tools.ToolRandoms;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service(name = BuyProductService.serviceName)
public class BuyProductService extends BaseService {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(BuyProductService.class);
	public static final String serviceName = "buyProductService";

	/**
	 * 获取新的订单编号
	 * 
	 */
	public static String getOrderNumber(String organids) {
		// 获取当月
		SimpleDateFormat df = new SimpleDateFormat("yyMM");
		String date = df.format(new Date());
		// 获取机构编号（门店编号）
		String dlmdBH = BentryRegisterService.getOrgBh(organids);
		String p = "%" + date + dlmdBH + "%";
		String sql = getSqlMy(ProductSalesOrder.sqlId_sleBh);
		List<ProductSalesOrder> psoList = ProductSalesOrder.dao.find(sql, p);
		if (psoList != null && psoList.size() > 0) {
			String ornum = psoList.get(0).getStr(ProductSalesOrder.column_orderNumber);
			int n = Integer.parseInt(ornum.substring(ornum.length() - 4, ornum.length()));
			String newNum = date + dlmdBH + String.format("%04d", n + 1);
			return newNum;
		} else {
			String newNum = date + dlmdBH + "0001";
			return newNum;
		}
	}
	/**
	 * 根据顾客ids查出协议中需要购买的疗程
	 */
	public Map<String, Object> getCusAgrLc(String cusId, String orgid) {
		Map<String, Object>   mm=new HashMap<>();
		String msg=ConstantRender.render_success_code;
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("column", CustomerAgreement.column_customerID);
		String sql = getSqlByBeetl(CustomerAgreement.sqlId_column, param);
		CustomerAgreement ca = CustomerAgreement.dao.findFirst(sql, cusId);
		// 顾客未支付
		if (ca != null && ca.getStr(CustomerAgreement.column_isPay).equals("0")) {
			Map<String, String> lcMap = new HashMap<>();
			Product p = Product.dao.findById(ca.getStr(CustomerAgreement.column_codeIds));
			if (p != null) {
				// 查出产品价格表
				String dlcsql = getSqlMy(Product.sqlId_selProByIds);
				Product dlc = Product.dao.findFirst(dlcsql, p.getStr(Product.column_ids), orgid);
				if (dlc != null) {
					if (p.getStr(Product.column_proUnits).equals(Code.dlc_units)) {
						float total = dlc.getFloat(ProductPrice.column_outPrice);
						lcMap.put("number", "1");
						lcMap.put("total", total + "");
					} else if (p.getStr(Product.column_proUnits).equals(Code.bzlc_units)
							&& p.getStr(Product.column_proCapacity).equals(Code.ylc_capacity)) {
						// 单疗程 通过id查出价格
						float total = dlc.getFloat(ProductPrice.column_outPrice);
						lcMap.put("number", "1");
						lcMap.put("total", total + "");
					} else {
						// 标准疗程 通过id查出价格
						float total = dlc.getFloat(ProductPrice.column_outPrice)
								* ca.getInt(CustomerAgreement.column_treatment);
						lcMap.put("number", ca.getInt(CustomerAgreement.column_treatment).toString());
						lcMap.put("total", total + "");

					}

					lcMap.put("outprice", dlc.getFloat(ProductPrice.column_outPrice) + "");
				} else {
					msg="疗程产品价格未设置";
				}
				Code co = Code.dao.findById(Code.lc_ids);
				lcMap.put("ids", p.getStr(Product.column_ids));
				lcMap.put("probh", p.getStr(Product.column_proBh));
				lcMap.put("name", p.getStr(Product.column_name));
				lcMap.put("typename", co.getStr(Code.column_name));
				mm.put("msg", msg);
				mm.put("lcMap",lcMap);
				return mm;
			} 
		}
		return null;
	}

	
	
	
	
	/**
	 * 产品购买结算
	 */
	public String settlement(String organids, String userIds, String customerIds, String receivable, String proceeds,
			String orderNumber, String paymentWay, String proInfo,String xsr,String cpbh) {
		String msg = "";
		
		/*System.out.println(StringUtils.isNotBlank(cpbh));
		System.out.println(proInfo.contains("塑形"));*/
		if(!StringUtils.isNotBlank(cpbh)&&proInfo.contains("塑形")){
			msg = "产品编号不能为空";
			return msg;
		}else {
		
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("column",CustomerDetail.column_customerIds);
			String sql = getSqlByBeetl(CustomerDetail.sqlId_column, param);
			CustomerDetail customerDetail = CustomerDetail.dao.findFirst(sql,customerIds);
			if(customerDetail!=null){
				if(!StringUtils.isNotBlank(customerDetail.getStr(CustomerDetail.column_productNo))&&StringUtils.isNotBlank(cpbh)){
					String sql1 = " select productNo from  sb_customer_detail  where dataStatus in ('1','2') and organIds = ? and customerIds !=?  and  productNo = ?";
					List<Record> cbis = Db.find(sql1,organids,customerIds,cpbh);
					if(cbis==null||cbis.size()==0){
						customerDetail.set(CustomerDetail.column_productNo, cpbh);
						if(!customerDetail.update()){
							msg = "产品编号保存失败";
							return msg;
						}
					}else{
						msg = "产品编号已经存在，请重新输入";
						return msg;
					}
					
				}
			
			
		Customer  c=Customer.dao.findById(customerIds);
		if (c != null) {
			// 保存销售订单
			ProductSalesOrder pso = new ProductSalesOrder();
			String psoids = ToolRandoms.getUuid(true);
			pso.set(ProductSalesOrder.column_ids, psoids).set(ProductSalesOrder.column_orderNumber, orderNumber)
					.set(ProductSalesOrder.column_customerIds, c.getStr(Customer.column_ids))
					.set(ProductSalesOrder.column_organIds, organids).set(ProductSalesOrder.column_userIds, xsr)
					.set(ProductSalesOrder.column_receivable, receivable)
					.set(ProductSalesOrder.column_proceeds, proceeds)
					.set(ProductSalesOrder.column_paymentWay, paymentWay)
					.set(ProductSalesOrder.column_arrears, Integer.parseInt(receivable) - Integer.parseInt(proceeds))
					.set(ProductSalesOrder.column_date, new Date()).set(ProductSalesOrder.column_gxsj, new Date());
			
			if (!pso.save()) {
				log.debug("保存产品订单失败！！");
				throw new RuntimeException("保存产品订单失败!");
			}

			JSONArray json = JSONArray.fromObject(proInfo);
			if (json.size() > 0) {
				for (int i = 0; i < json.size(); i++) {
					JSONObject job = json.getJSONObject(i); // 遍历 jsonarray数组，把每一个对象转成 json对象
					// 根据ids查出产品
					Product p = Product.dao.findById(job.get("ids"));
					if (p != null) {
						SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
						String gxsj = "%" + dateFormater.format(new Date()) + "%";
						// 购买的产品总容量
						float capacities = Float.parseFloat(job.get("number").toString())
								* Integer.parseInt(p.getStr(Product.column_proCapacity));
						
						// 购买的产品总经验值
						float totalException = 0f;
						//如果门店设置了产品总经验值按门店设置的值
						String sqlExp = "SELECT * FROM sb_product_orgexperience where organIds = ? and productIds = ? and dataStatus =1";
						ProductOrgExperience productOrgExperience = ProductOrgExperience.dao.findFirst(sqlExp,organids,p.getStr(Product.column_ids));
						if(productOrgExperience!=null){
							//门店没设置
							 totalException = Float.parseFloat(job.get("number").toString())
										*productOrgExperience.getFloat(ProductOrgExperience.column_totalExperience);
						}else{
							//门店没设置
							 totalException = Float.parseFloat(job.get("number").toString())
									* Integer.parseInt(p.getStr(Product.column_proExperience)==null?"0":p.getStr(Product.column_proExperience));
						}
						

						// 查询顾客是否已有此产品
						String cpsql = getSqlMy(CustomerProduct.sqlId_selByCusAndPro);
						CustomerProduct cuspro = CustomerProduct.dao.findFirst(cpsql, c.getStr(Customer.column_ids),
								p.getStr(Product.column_ids), organids);
						if (cuspro != null) {
							if (p.getStr(Product.column_typeIds).equals(Code.lc_ids)) {
								log.debug("已经购买过疗程！！");
								throw new RuntimeException("已经购买过疗程产品，如需更改请在疗程转型中购买!");
							} else { 
								// 跟新顾客产品信息
								cuspro.set(CustomerProduct.column_count,
										cuspro.getInt(CustomerProduct.column_count)
												+ Float.parseFloat(job.get("number").toString()))
//										.set(CustomerProduct.column_capacities,
//												capacities + cuspro.getFloat(CustomerProduct.column_capacities))
										.set(CustomerProduct.column_totalExperience,
												totalException+cuspro.getFloat(CustomerProduct.column_totalExperience))
										.set(CustomerProduct.column_updateDate, new Date()).update();
							}

						} else {
							// 保存顾客产品记录
							CustomerProduct cp = new CustomerProduct();
							String cids = ToolRandoms.getUuid(true);
							cp.set(CustomerProduct.column_ids, cids).set(CustomerProduct.column_organids, organids)
									.set(CustomerProduct.column_customerID, c.getStr(CustomerProduct.column_ids))
									.set(CustomerProduct.column_productID, job.get("ids"))
									.set(CustomerProduct.column_count, job.get("number"))
									.set(CustomerProduct.column_proUnitPrice, job.get("outprice"))
									.set(CustomerProduct.column_capacity, p.getStr(Product.column_proSpecification))
									.set(CustomerProduct.column_capacities, capacities)
									.set(CustomerProduct.column_proExperience, p.getStr(Product.column_proExperience))
									.set(CustomerProduct.column_totalExperience, totalException)
									.set(CustomerProduct.column_productNo, cpbh)
									.set(CustomerProduct.column_updateDate, new Date());
							if (!cp.save()) {
								log.debug("保存顾客产品失败！！");
								throw new RuntimeException("保存顾客产品失败!");
							}
						}
						//查询顾客在当日有无产品明细存在
						CustomerProductSurplus  cps=CustomerProductSurplus.dao.getCustomerProductSurplus(customerIds, p.getStr(Product.column_ids), organids, gxsj);
						if(cps!=null)
						{	
							//更新顾客产品明细
							cps.set(CustomerProductSurplus.column_totalExperience, totalException+cps.getFloat(CustomerProductSurplus.column_totalExperience))
								.set(CustomerProductSurplus.column_count, Integer.parseInt(job.get("number").toString())+cps.getInt(CustomerProductSurplus.column_count))
								.set(CustomerProductSurplus.column_gxsj, new Date());
							if (!cps.update()) {
								log.debug("更新顾客产品明细失败！！");
								throw new RuntimeException("更新顾客产品明细失败!");
							}
							
						}else
						{
							//保存顾客产品明细
							CustomerProductSurplus  cusprosur=new CustomerProductSurplus();
							cusprosur.set(CustomerProductSurplus.column_ids, ToolRandoms.getUuid(true))
									.set(CustomerProductSurplus.column_organIds, organids)
									.set(CustomerProductSurplus.column_customerIds, customerIds)
									.set(CustomerProductSurplus.column_productIds, p.getStr(Product.column_ids))
									.set(CustomerProductSurplus.column_count, job.get("number"))
									.set(CustomerProductSurplus.column_proExperience,  p.getStr(Product.column_proExperience))
									.set(CustomerProductSurplus.column_totalExperience, totalException)
									.set(CustomerProductSurplus.column_gxsj, new Date());
							if (!cusprosur.save()) {
								log.debug("保存顾客产品明细失败！！");
								throw new RuntimeException("保存顾客产品明细失败!");
							}
						}
						
						// 保存店面销售记录
						String psids = ToolRandoms.getUuid(true);
						ProductSales ps = new ProductSales();
						ps.set(ProductSales.column_ids, psids)
								.set(ProductSales.column_orderIds, pso.getStr(ProductSalesOrder.column_ids))
								.set(ProductSales.column_organids, organids)
								.set(ProductSales.column_customerID, c.getStr(CustomerProduct.column_ids))
								.set(ProductSales.column_type, p.getStr(Product.column_typeIds))
								.set(ProductSales.column_productID, job.get("ids"))
								.set(ProductSales.column_number, job.get("number"))
								.set(ProductSales.column_userID, xsr)
								.set(ProductSales.column_unitPrice, job.get("outprice"))
								.set(ProductSales.column_price, job.get("total"))
								.set(ProductSales.column_date, new Date())
								.set(ProductSales.column_consumerType, Code.xflb_gm);
						if (!ps.save()) {
							log.debug("保存产品销售记录失败！！");
							throw new RuntimeException("保存产品销售记录失败!");
						}

						if (!p.getStr(Product.column_typeIds).equals(Code.lc_ids)) {
							// 更新产品库存
							String pstids = ToolRandoms.getUuid(true);
							
							// 根据日期和机构id,产品id查出当日是否有库存记录
							String pstInsql = getSqlMy(ProductStockInfo.sqlId_selByOidsAndPidsAndTime);
							String pstSql = getSqlMy(ProductStock.sqlId_selPSByOidsAndPids);
							ProductStockInfo psi = ProductStockInfo.dao.findFirst(pstInsql, organids, job.get("ids"),
									gxsj);
							ProductStock pst = ProductStock.dao.findFirst(pstSql, organids, job.get("ids"));
		//					System.out.println( pst.getFloat(ProductStock.column_num));
		//					System.out.println(Float
		//							.parseFloat(job.get("number").toString()));
							if (pst != null && pst.getFloat(ProductStock.column_num) >= Float
									.parseFloat(job.get("number").toString())) {

								float num1 = pst.getFloat(ProductStock.column_num)
										- Float.parseFloat(job.get("number").toString());
								pst.set(ProductStock.column_num, num1).set(ProductStock.column_gxsj, new Date());
								if (!pst.update()) {
									log.debug("更新产品总库存失败");
									throw new RuntimeException("更新产品总库存失败!");
								}
								if (psi != null) {
									// 库存详细信息减少库存
									float num = psi.getFloat(ProductStockInfo.column_stock)
											- Float.parseFloat(job.get("number").toString());
									psi.set(ProductStockInfo.column_stock, num)
											.set(ProductStockInfo.column_gxsj, new Date()).update();

								} else {
									ProductStockInfo psInfo = new ProductStockInfo();
									String psinfoids = ToolRandoms.getUuid(true);
									psInfo.set(ProductStockInfo.column_ids, psinfoids)
											.set(ProductStockInfo.column_organids, organids)
											.set(ProductStockInfo.column_productID, job.get("ids"))
											.set(ProductStockInfo.column_type, p.getStr(Product.column_typeIds))
											.set(ProductStockInfo.column_stock, pst.getFloat(ProductStock.column_num))
											.set(ProductStockInfo.column_gxsj, new Date());
									if (!psInfo.save()) {
										log.debug("保存产品库存记录失败！！");
										throw new RuntimeException("保存产品库存记录失败!");
									}
								}
							} else {
								log.debug(p.getStr(Product.column_name) + "库存不够，无法购买！！");
								throw new RuntimeException(p.getStr(Product.column_name) + "库存不够，请先入库！！");
							}
						}
						if (p.getStr(Product.column_typeIds).equals(Code.lc_ids)) {
							log.debug("顾客已购买疗程，更新顾客协议购买状态");
							Map<String, Object> pp = new HashMap<String, Object>();
							pp.put("column", CustomerAgreement.column_customerID);
							String casql = getSqlByBeetl(CustomerAgreement.sqlId_column, pp);
							CustomerAgreement ca = CustomerAgreement.dao.findFirst(casql,
									c.getStr(Customer.column_ids));
							ca.set(CustomerAgreement.column_isPay, "1");
							if (!ca.update()) {
								log.debug("更新顾客协议购买状态失败");
								throw new RuntimeException("更新顾客协议购买状态失败");
							}
						}
						
						//保存日护理综合查询表
						DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(organids, new Date());
						if(dnt != null)
						{
							dnt.set(p.getStr(Product.column_proBh)+"SalNum", dnt.getInt(p.getStr(Product.column_proBh)+"SalNum")+Integer.parseInt(job.get("number").toString()))
								.set(p.getStr(Product.column_proBh)+"SalPrice", dnt.getDouble(p.getStr(Product.column_proBh)+"SalPrice")+Double.parseDouble(job.get("total").toString()))
								.set(DailyNursingTotal.column_priceTotal, dnt.getDouble(DailyNursingTotal.column_priceTotal)+Double.parseDouble(job.get("total").toString()));
							if (p.getStr(Product.column_typeIds).equals(Code.lc_ids) || p.getStr(Product.column_typeIds).equals(Code.dlc_ids)) 
							{
								dnt.set(DailyNursingTotal.column_jzzxse, dnt.getDouble(DailyNursingTotal.column_jzzxse)+Double.parseDouble(job.get("total").toString()));
							}
							if (!dnt.update()) {
								log.debug("更新日护理综合查询表失败");
								throw new RuntimeException("更新日护理综合查询表失败");
							}
						}else
						{
							 dnt = new DailyNursingTotal();
							 dnt.set(DailyNursingTotal.column_organids, organids)
							 	.set(DailyNursingTotal.column_date, new Date())
							 	.set(p.getStr(Product.column_proBh)+"SalNum", Integer.parseInt(job.get("number").toString()))
								.set(p.getStr(Product.column_proBh)+"SalPrice", Double.parseDouble(job.get("total").toString()))
								.set(DailyNursingTotal.column_priceTotal,Double.parseDouble(job.get("total").toString()));
							 if (p.getStr(Product.column_typeIds).equals(Code.lc_ids) || p.getStr(Product.column_typeIds).equals(Code.dlc_ids)) 
							{
								dnt.set(DailyNursingTotal.column_jzzxse, Double.parseDouble(job.get("total").toString()));
							}
							 if (!dnt.save()) {
									log.debug("保存日护理综合查询表失败");
									throw new RuntimeException("保存日护理综合查询表失败");
							 }
						}
					
					}
				}
			}

			msg = ConstantRender.render_success;
			return msg;
		} else {
			log.debug("根据姓名和身份证查出顾客为空");
			throw new RuntimeException("当前顾客不存在！请重新输入！！");
		}
		
		}
	}
		return msg;
	}
}
